#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "build_tlv.h"
#include "tcp_socket.h"

#define DEBUG 1
#define LOGD(fmt, ...) {if (DEBUG == 1 ) printf("[D][%s:%d] "fmt"\n", __FUNCTION__, __LINE__, ##__VA_ARGS__);}

static const int count      = 100;         // tag: 1022
static const char hello[10] = "Hello TLV"; // tag: 1023
static const char *into     = "test";      // tag: 1024

static void tlv_test()
{
    /* TLV_MSG 结构体 */
    struct TLV_MSG tlvMsg;
    memset(&tlvMsg, 0x00, sizeof(tlvMsg));

    /* 最终组建的tlv消息buffer */
    char buffer[4096] = {0};
    memset(buffer, 0x00, sizeof buffer);

    /* 添加TLV的BODY，这儿只传入tlvBodyType、 tlvBodyTag、和BODY具体的内容value即可 */
    tlvMsg.tlvBody.tlvBodyType = TLV_BODY_TYPE_INT;
    tlvMsg.tlvBody.tlvBodyTag  = 1022;
    build_tlv_msg(&tlvMsg, buffer, (void *)(&count));

    /* 添加TLV的BODY，这儿只传入tlvBodyType、 tlvBodyTag、和BODY具体的内容value即可 */
    tlvMsg.tlvBody.tlvBodyType = TLV_BODY_TYPE_STRING;
    tlvMsg.tlvBody.tlvBodyTag  = 1023;
    build_tlv_msg(&tlvMsg, buffer, (void *)hello);

    /* 添加TLV的BODY，这儿只传入tlvBodyType、 tlvBodyTag、和BODY具体的内容value即可 */
    tlvMsg.tlvBody.tlvBodyType = TLV_BODY_TYPE_STRING;
    tlvMsg.tlvBody.tlvBodyTag  = 1024;
    build_tlv_msg(&tlvMsg, buffer, (void *)into);


    /* 通过TCP短链接发送消息 */
    struct TCP_MSG *tcpMsg = NULL;
    tcpMsg = (struct TCP_MSG *)calloc(1, sizeof(struct TCP_MSG));
    tcpMsg->msgLength = tlvMsg.tlvHead.tlvHeadLength;

    tcpMsg->msg = (char *)calloc(1, sizeof(char) * tcpMsg->msgLength);
    memcpy(tcpMsg->msg, buffer, tcpMsg->msgLength);

    send_message(tcpMsg);

    free(tcpMsg->msg);
    tcpMsg->msg = NULL;
    free(tcpMsg);
    tcpMsg = NULL;
}

int main() {

    tlv_test();

    return 0;
}
